export default {
  mounted(el, binding) {
    // 初始状态设置
    el.dataset.src = binding.value; // 存储真实图片路径
    el.src = binding.arg || "data:image/svg+xml;base64,..."; // 默认loading图

    // 创建观察器
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            loadImage(el);
          }
        });
      },
      { threshold: 0.1 }
    );

    observer.observe(el);
    el._observer = observer; // 保存观察器实例用于销毁
  },
};

// 图片加载逻辑
function loadImage(el) {
  const img = new Image();
  const realSrc = el.dataset.src;

  // 显示loading状态
  el.src = "/src/assets/image/loading.gif";

  img.onload = () => {
    // 成功时替换为真实图片
    el.src = realSrc;
    el.classList.add("loaded");
  };

  img.onerror = () => {
    // 失败时显示错误占位图
    el.src = "/src/assets/image/error.png";
    el.classList.add("error");
  };

  img.src = realSrc;
  el._img = img; // 保存图片实例
}

// 指令解绑时清理资源
export function unbind(el) {
  el._observer?.disconnect();
  delete el._observer;
  delete el._img;
}
